package cn.sjtu.security.servicce.Impl;

import cn.sjtu.security.entity.Auth;
import cn.sjtu.security.mapper.AuthMapper;
import cn.sjtu.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现UserDetailsService从数据库查询数据，认证服务器实现的关键
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    // 从内存中查询用户
//    @Override
//    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        UserDetails syo = User.withUsername("syo").password(passwordEncoder.encode("123456")).authorities("world").build();
//        return syo;
//    }

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        cn.sjtu.security.entity.User user = userMapper.queryOneByUsername(username);

        if(user == null)
            throw new UsernameNotFoundException("用户名或密码错误");

        List<Auth> authList = authMapper.queryAuthsByUid(user.getId());
        List<String> auths = new ArrayList<>();

        for (Auth a: authList) {
            auths.add(a.getCode());
        }

        String[] array = auths.toArray(new String[auths.size()]);


        return User
                .withUsername(username)
                .password(user.getPassword())
                .authorities(array)
                .build();
    }
}
